package cn.jekun.shop.web.service;

import java.sql.Types;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.DateJsonValueProcessor;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Mobile;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.shop.common.service.ShopBaseService;
import cn.jekun.shop.web.bean.UserStat;

@Service(UserService.BEAN_NAME)
public class UserService extends ShopBaseService{

	public static final String BEAN_NAME = "cn.jekun.shop.web.service.UserService";
	
	@Override
	public String getNamespace() {
		return "SHOP_USER";
	}
	@Resource(name=RsUserService.BEAN_NAME)
	RsUserService rsUserService;
	/**
	 * 获取个人的统计信息(
	 * 		积分：5620 
			待收货订单：1份 
			待付款订单：2份 
			已成功订单：
	 * @param userId
	 * @return
	 */
	public JSONObject getStatInfo(@RsUser.AnnoUserId String userId) {
		JSONObject jsonObject = new JSONObject();
		//基本验证
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不能为空");
		}
		try{
			Map map = new HashMap();
			map.put("userId", userId);
			UserStat userOrderStat = this.one(this.getStatementName("userOrderStat"), map);
			UserStat userCreditsStat = this.one(this.getStatementName("userCreditsStat"), map);
			if (userOrderStat == null) {
				userOrderStat = new UserStat();
			}
			if (userCreditsStat!=null) {
				userOrderStat.setUserName(userCreditsStat.getUserName());
				userOrderStat.setCreditsTotal(userCreditsStat.getCreditsTotal());
			}
			return this.executeRerutn(JSONObject.fromObject(userOrderStat));
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}
	/**
	 * 获取用户信息
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject getUserInfo(@RsUser.AnnoUserId String userId){
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码为空");
		}
		Map userMap = new HashMap();
		userMap.put(RsUser.COL_USER_ID, userId);
		SqlUtis.prepareSql(userMap,
				SqlUtis.getSQL(userMap, "a."
				+ RsUser.COL_USER_ID,Types.VARCHAR,SqlUtis.EQ));
		RsUser rsUser = this.rsUserService.one(userMap);
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		if(rsUser == null){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户信息不存在");
		}
		rsUser.setPassword("");
		String tempIconUrl = rsUser.getIconUrl();
		rsUser.setIconUrl(tempIconUrl);
		JSONObject json =  JSONObject.fromObject(rsUser, jsonConfig);
		jsonObject.put("RsUser", json);
		return executeRerutn(jsonObject);
	}
	/**
	 * 更新用户信息
	 * @param userId
	 * @param userName
	 * @param mobile
	 * @param sex
	 * @param birthday
	 * @param phone
	 * @param email
	 * @param address
	 * @param zipCode
	 * @param myFile
	 * @param myFileFileName
	 * @param myFileContentType
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject updateUserInfo(@RsUser.AnnoUserId String userId, @RsUser.AnnoUserName String userName,
			@Mobile String mobile, @RsUser.AnnoSex String sex,@RsUser.AnnoBirthday String birthday, @RsUser.AnnoPhoneNumber String phone,
			@RsUser.AnnoEmail String email, @RsUser.AnnoAddress String address,@RsUser.AnnoZipcode String zipCode,@RsUser.AnnoRealName String realName,@RsUser.AnnoIconUrl String iconUrl) throws Exception {
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		RsUser rsUser = new RsUser();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码为空");
		}
		if (StringUtils.isBlank(userName)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户名为空");
		}
		/*if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机号为空");
		}*/
		/*if (StringUtils.isBlank(email)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"邮箱不能为空");
		}*/
		/*if(StringUtils.isNotBlank(birthday)){
			  DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
			  Date userBirthday = fmt.parse(birthday);
			  rsUser.setBirthday(userBirthday);
		}*/
/*		Map tempUserMap = new HashMap();
		tempUserMap.put(RsUser.COL_USER_ID, userId);
		tempUserMap.put(RsUser.COL_USER_NAME, userName);
		tempUserMap.put(RsUser.COL_MOBILE, mobile);
		SqlUtis.prepareSql(tempUserMap,"",SqlUtis.getSQL(tempUserMap, "a."+ RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
		RsUser tempUser = new RsUser();
		tempUser = this.rsUserService.one(tempUserMap);
		
		if(tempUser != null){
			//如果用户名变则验证
			if(!tempUser.getUserName().equals(userName)){
				SqlUtis.prepareSql(tempUserMap,"",SqlUtis.getSQL(tempUserMap, "a."+ RsUser.COL_USER_NAME, Types.VARCHAR,SqlUtis.EQ));
				if(this.rsUserService.exists(tempUserMap)){
					throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
							"用户名已存在");
				}
			}
			//如果手机有变则验证
			else if(!tempUser.getMobile().equals(mobile)){
				SqlUtis.prepareSql(tempUserMap,"",SqlUtis.getSQL(tempUserMap, "a."+ RsUser.COL_MOBILE, Types.VARCHAR,SqlUtis.EQ));
				if(this.rsUserService.exists(tempUserMap)){
					throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
							"手机号已存在");
				}
				
			}
			rsUser.setMobile(mobile);
			rsUser.setUserName(userName);
			
		}*/
		//rsUser.setAddress(address);
		rsUser.setUserId(userId);
		rsUser.setRealName(realName);
		rsUser.setEmail(email);
		//rsUser.setSex(sex);
		//rsUser.setZipcode(zipCode);
		//rsUser.setPhoneNumber(phone);
		
		/*String fileName = "";
		String uploadPath = "";
		if(myFile != null && myFile[0] != null){
			if(myFile.length == 1){
				InputStream is = new FileInputStream(myFile[0]); 
				uploadPath = this.getFileSystem() + "/userIcons/";
				// 设置目标文件
				fileName = userId+ "."+ StringUtils.substringAfterLast(myFileFileName[0], ".");
				File toFile = new File(uploadPath,fileName);
				if (!toFile.getParentFile().exists()) {
					toFile.getParentFile().mkdirs();
				}
				// 创建一个输出流
				OutputStream os = new FileOutputStream(toFile);
				// 设置缓存
				byte[] buffer = new byte[1024];
				int length = 0;
				// 读取myFile文件输出到toFile文件中
				while ((length = is.read(buffer)) > 0) {
					os.write(buffer, 0, length);
				}
				// 关闭输入流
				is.close();
				// 关闭输出流
				os.close();
			}*/
			rsUser.setIconUrl(iconUrl);
		/*}*/
		/*formMap.put(RsUser.COL_USER_ID, userId);
		formMap.put("rsUser", rsUser);
		SqlUtis.prepareSql(formMap,"",SqlUtis.getSQL(formMap, "a."+ RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));*/
		int count = this.rsUserService.update(rsUser);
		if(count != 1){
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);
	}
}
